package user

import (
	"common/comCopier"
	"common/dao/model"
	"context"
	"errors"
	"gateway/internal/svc"
	"gateway/internal/types"
	"gorm.io/gorm"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterUser) (resp *types.Emp, err error) {
	// todo: add your logic here and delete this line
	var (
		user  model.User
		Fuses model.User
	)

	err = comCopier.CopyWithOption(&user, req)
	user.CreateTime = time.Now().Unix()
	user.UpdateTime = time.Now().Unix()
	db := l.svcCtx.DB.Table(model.TableNameUser)
	err = db.Transaction(func(tx *gorm.DB) error {

		if err := tx.Where("isDel = ?", 0).Where("account = ?", user.Account).First(&Fuses).Error; err != nil {
			return err
		}
		if Fuses.ID > 0 {
			return errors.New("账户已存在")
		}
		if err := tx.Create(&user).Error; err != nil {
			return err
		}
		return nil
	})
	return
}
